package de.lulusoft.anothertorrent.core.xmlrpc;

import java.net.MalformedURLException;
import java.net.URL;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;


public class XmlrpcManager extends ConnectionManager{
	
	private XmlRpcClientConfigImpl config = null;
	private XmlRpcClient client = null;
	private String m_url = null;

	public XmlrpcManager(String url, boolean i8Support)throws XmlRpcException
	{	
		m_url = url;
		m_I8Support = i8Support;
	}
	
	
	@Override
	public void connect() throws XmlRpcException
	{
		config = new XmlRpcClientConfigImpl();
		config.setEnabledForExtensions(true);
	    try {
			config.setServerURL(new URL(m_url));
			m_connected = true;
		} catch (MalformedURLException e) {
			throw new XmlRpcException(e.getMessage());
		}
	    client = new XmlRpcClient();
	    client.setConfig(config);
	    client.setTypeFactory(new RTorrentTypeFactory(client, m_I8Support));
	}
	
	@Override
	public void disconnect()
	{
		super.disconnect();
	}
	
	@Override
	public Object sendSimpleCommand(String cmd)throws XmlRpcException
	{
		if (!m_connected)
			throw new XmlRpcException(ERROR_NOT_CONNECTED);
		Object[] params = new Object[]{};
		Object result = null;
		result = client.execute(cmd, params);

		return result;
	}
	
	@Override
	public Object sendCommand(String cmd, Object[] params)throws XmlRpcException
	{
		if (!m_connected)
			throw new XmlRpcException(ERROR_NOT_CONNECTED);
		Object result = null;
		
		result = client.execute(cmd, params);
		
		return result;
	}
}
